package com.tedu.cooshark.controller;

import com.tedu.cooshark.entity.User;
import com.tedu.cooshark.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 2022/3/24  11:47
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session, HttpServletResponse res){
        System.out.println("登录用户"+user.toString());
        User user1 = userService.selectBylogin(user);
        if (user1!=null){
            session.setAttribute("user",user1);
            if(user.isRem()){
                Cookie c1=new Cookie("username", user.getUsername());
                Cookie c2=new Cookie("password", user.getPassword());
                c1.setMaxAge(60*60*24*30);
                c2.setMaxAge(60*60*24*7);
                res.addCookie(c1);
                res.addCookie(c2);
            }
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User)session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
         session.removeAttribute("user");
    }
}
